package com.task.controller.control;

import com.task.controller.annotation.impl.FunctionImpl;
import com.task.controller.executor.Executor;
import com.task.controller.executor.impl.AsyncExecutor;
import com.task.controller.executor.impl.CurrentExecutor;
import com.task.controller.executor.impl.UIExecutor;
import com.task.controller.manager.impl.AsyncMethodManager;
import com.task.controller.manager.impl.CurrentMethodManager;
import com.task.controller.manager.impl.UIMethodManager;
import ohos.app.Context;

import java.lang.reflect.InvocationTargetException;

public abstract class AbstractControl implements Control {

    protected Context context;

    @Override
    public void initControl(Context context) {
        this.context = context;
        try {
            FunctionImpl.initFunction(context);
        } catch (InvocationTargetException | IllegalAccessException | InstantiationException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void execute(String resource, Object param, Executor.ExecuteEvent executeEvent) {
        AsyncMethodManager asyncMethodManager = AsyncMethodManager.getInstance();
        CurrentMethodManager currentMethodManager = CurrentMethodManager.getInstance();
        UIMethodManager uiMethodManager = UIMethodManager.getInstance();
        if (asyncMethodManager.containsKey(resource)) {
            AsyncExecutor.getInstance().execute(context, resource, param, executeEvent);
        } else if (currentMethodManager.containsKey(resource)) {
            CurrentExecutor.getInstance().execute(context, resource, param, executeEvent);
        } else if (uiMethodManager.containsKey(resource)) {
            UIExecutor.getInstance().execute(context, resource, param, executeEvent);
        } else {
            throw new IllegalStateException("没有要触发的资源：".concat(resource));
        }
    }

    @Override
    public void release() {
        AsyncMethodManager.getInstance().clear();
        CurrentMethodManager.getInstance().clear();
        UIMethodManager.getInstance().clear();
    }
}
